#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys, types
import urllib2, cookielib
import ClientForm
#import socks
#from socksipyhandler import *

class HttpClient(object):
    def __init__(self, timeout = 5.0):
        #self.sockshandler = SocksiPyHandler(socks.PROXY_TYPE_SOCKS4, '192.168.1.1', 9090)
        self.cookies = cookielib.CookieJar()
        self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookies))
        self.timeout = timeout
    def request(self,*arg, **karg):
        req = urllib2.Request(*arg,**karg)
        return req
    def open(self, req):
        res = self.opener.open(req, timeout=self.timeout)
        if not hasattr(res,'data'):
            res.data = res.read()
        return res

class myform(object):
    def __init__(self, d, host):
        self.form = ClientForm.ParseFile(d, "http://{}".format(host))[0]
        self.ctls = self.form.controls
    def _find(self, name):
        for c in self.ctls:
            if c.name != None and c.name.find(name) >= 0:
                return c
        return None
    def data(self):
        data = self.form._request_data()
        return data[1]
    def fill(self, branch, plat, rtype, btype, cl = None):
        if cl != None:
            self._find('SYNCATCL]').value = cl
        self._find('CodeStream]').value = [branch]
        self._find('ADB_PLATFORMTYPE]').value = [plat]
        self._find('ADB_RELEASETYPE]').value = [rtype]
        self._find('ADB_BUILDTYPE]').value = [btype]

class bfClient(HttpClient):
    def __init__(self, host):
        super(bfClient,self).__init__()
        self.host = host
    def _request(self, url, data= None, **hdrs):
        headers = {"User-Agent":"Mozilla/5.0 Gecko/20130101 Firefox/28.0",
                   "Accept-Encoding": "gzip, deflate",
                   "Connection": "close",
                   "Pragma": "no-cache"
                   }
        headers.update(hdrs)
        req = self.request(url,origin_req_host=self.host,headers= headers, data= data)
        return req
    def auth(self):
        if user == None or password == None:
            print("Invalid credentials")
            sys.exit(1)
        req = self._request("http://{}/".format(self.host) , data= "username={}&password={}&submit=Login".format(user, password), Referer="http://{}/".format(self.host) )
        res = self.open(req)
        data = res.data
        if data.find('class="error"') >= 0 :
            print("Invalid credentials")
            sys.exit(1)
    def jobs(self):
        req = self._request('http://{}/fullcontrol/index.php?mod=jobs'.format(self.host))
        res = self.open(req)
        data = res.data
        print(data)
    def sbuild(self, d = None):
        req = self._request('http://{}/fullcontrol/index.php?mod=jobs&action=start&bf_id=319'.format(self.host), data = d, Referer='http://{}/fullcontrol/index.php?mod=jobs&action=start.list'.format(self.host))
        res = self.open(req)
        return res.data
    def round(self,branch, plat, rtype, btype, cl):
        data = self.sbuild()
        mf = myform(data,self.host)
        mf.fill(branch, plat, rtype, btype, cl)
        self.sbuild(mf.data())

        
def trigger(br = 'R', btype = 'DAILY', cl = None, host = 'usecspdbforge'):
    bf = bfClient(host)
    bf.auth()
    br = 'M-Branch'+ br
    bf.round(br, 'x64', 'nonprod', btype, cl)
    bf.round(br, 'x64', 'prod', btype, cl)
    bf.round(br, 'x86', 'nonprod', btype, cl)
    bf.round(br, 'x86', 'prod', btype, cl)
    
def main(argv):
    from optparse import OptionParser
    parser = OptionParser("Usage: %prog [options] <branch> <type>")
    parser.add_option("-u", "--user", action="store", type="string", metavar='<user name>', help='build forge user name')
    parser.add_option("-p", "--password", action="store", type="string", metavar='<password>', help='build forge password')
    parser.add_option("-c", "--changelist", action="store", type="string", metavar='<sync at CL>', help='sync at CL')
    parser.add_option("-s", "--bfserver", action="store", type="string", default='usecspdbforge', metavar='<build forge server>', help='build forge server')
    
    options, args = parser.parse_args(argv)
    if not args or len(args) != 2:
        parser.print_help()
        sys.exit(1)
    global user,password
    user = options.user
    password = options.password
    trigger(args[0].upper(), args[1].upper(), options.changelist.upper() if options.changelist else None, options.bfserver)
        
if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))